#region Telligent Copyright Header

//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

#endregion

#region Import Declarations

using System.IO;
using System;
using System.Security;
using System.Collections;
using System.Xml;
using CommunityServer.Components;
using System.Collections.Generic;
using CommunityServer.Galleries.Components;
using CommunityServer.Galleries;

#endregion

namespace CommunityServerStuff.CSModules
{
    class AutoGalleryCreateInRoleGroup : ICSModule
    {

        #region Private Members

        private Hashtable roleMappings = new Hashtable();

        #endregion

        #region Methods

        #region Constructor

        public AutoGalleryCreateInRoleGroup() { }

        #endregion

        #region Init

        public void Init(CSApplication csa, XmlNode node)
		{
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.Name == "RoleMapping")
                {
                    roleMappings.Add(childNode.Attributes["RoleName"].Value.ToLower(), int.Parse(childNode.Attributes["GroupId"].Value));
                }
            }
			csa.PostUserUpdate += new CSUserEventHandler(csa_PostUserUpdate);
        }

        #endregion

        #region csa_PostUserUpdate

        private void csa_PostUserUpdate(User user, CSEventArgs e)
		{
			if(user != null && e.State == ObjectState.Create)
			{
				GalleryConfiguration config = GalleryConfiguration.Instance();
				if(config.AutoCreateGallery)
				{
					string formattedKey = null;
					CSContext cSContext = CSContext.Current;
					Globals.ValidateApplicationKey(user.Username, out formattedKey);

					if(Globals.IsNullorEmpty(formattedKey) || Galleries.Exists(formattedKey))
					{
						return;
					}

					Gallery g = new Gallery();
					g.ApplicationKey = formattedKey;

                    int groupid = config.DefaultGroupID;

                    if (user.IsInRoles(roleMappings.Keys.ToString().Split(new char[]{','})))
                    {
                        foreach (string r in roleMappings.Keys)
                        {
                            if (System.Web.Security.Roles.IsUserInRole(user.Username, r))
                            {
                                groupid = (int)roleMappings[r];
                                EventLogs.Warn("RoleMapping found. Role: " + roleMappings[r].ToString(), "RoleGalleryCreate", 941);
                            }
                        }

                    }


                    //String[] userRoles = Ro Rolles.GetUserRoleNames(user.Username);
                    //for(int i = 0; i = userRoles.Length - 1; i++)
                    //{
                    //    if (Roles.IsBuiltInRole(userRoles[i]))
                    //    {
                    //        System.Web.Security.Roles.IsUserInRole(user.Username, userRoles[i]);
                    //    }
                    //}

                    //int groupid = config.DefaultGroupID;
                    if (groupid <= 0)
                    {
                        EventLogs.Warn("If we found a RoleMapping we shouldn't be here.", "RoleGalleryCreate", 941);
                        List<Group> groups = GalleryGroups.GetGroups(true, false, false);
                        if (groups.Count > 0)
                            groupid = groups[0].GroupID;
                    }

                    if (groupid <= 0)
                        return;

                    EventLogs.Warn("Final Group: " + groupid, "RoleGalleryCreate", 941);

                    g.GroupID = groupid;
                    g.Name = user.Username;
					g.IsActive = true;
					g.SettingsID = cSContext.SiteSettings.SettingsID;
					g.ApplicationType = ApplicationType.Gallery;
					g.DateCreated = DateTime.Now;
					g.Owners = user.Username;
					g.IsSearchable = true;
					g.EnableRss = true;

					//Create The Gallery
					g.SectionID = CommunityServer.Galleries.Galleries.AddGallery(g);

                    // Add the gallery url to the users profile
                    if (Globals.IsNullorEmpty(user.Profile.WebGallery))
                        user.Profile.WebGallery = Globals.FullPath(g.Url);

					//Create the Folder on the webserver
					try
					{
						if(GalleryConfiguration.Instance().CreateGalleryDirectories)
							WebDirectory.Create(Globals.GetSiteUrls().Locations["galleries"] + g.ApplicationKey);
					}
					catch(IOException ex)
					{ new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
					catch(SecurityException ex)
					{ new CSException(CSExceptionType.AccessDenied, "CreateGallery: Permission to add the folder on filesystem denied.", ex).Log(); }
					catch { }
			
					//Not Cluster safe, but lets try and update the cache
					CommunityServer.Galleries.Galleries.GetGalleries(cSContext.User.UserID, true, true, true);
				}
			}
        }

        #endregion

        #endregion
    }
}
